//
//  CYHomeTableViewController.swift
//  CYSinaWB
//
//  Created by mac on 16/1/30.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class CYHomeTableViewController: CYBaseTableViewController {
    
    //模型数组
    private lazy var statuses = [CYStatus]()
    //cellId
    private let cellId = "homeCellID"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin {
            //用户没有登录 当前的根视图是访客视图 就不要设置tableView
        visitorLoginView?.setupInfoWith("关注一些人，回这里看看有什么惊喜", imageName: nil)
            return
        }
//        tableView.rowHeight = 250
        tableView.estimatedRowHeight = 250
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.separatorStyle = .None
        prepareForTableView()
        loadData()
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    private func prepareForTableView() {
//        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.registerClass(CYStatusCell.self, forCellReuseIdentifier: cellId)
    }
   @objc private func loadData() {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let token = CYAccountViewModel.sharedViewModel.access_token else {
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        let parameters = ["access_token" : token]
        let AFN = AFHTTPSessionManager()
    refreshControl?.beginRefreshing()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            self.refreshControl?.endRefreshing()
            //转化为字典
            guard let dict = result as? [String : AnyObject] else {
                SVProgressHUD.showErrorWithStatus("数据类型不匹配")
                return
            }
            //在字典中通过"statuses"这个key 获取数据
            guard let array = dict["statuses"] as? [[String: AnyObject]] else {
                SVProgressHUD.showErrorWithStatus("数据类型不匹配")
                return
            }
            
            var tempArr = [CYStatus]()
            //遍历数组 获取单个对象
            for item in array {
                print(item["text"])
                let s = CYStatus(dict: item)
                tempArr.append(s)
            }
            
            self.statuses = tempArr
            
            self.tableView.reloadData()
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showErrorWithStatus("请检查网络")
        }
    }

}

extension CYHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! CYStatusCell
//        cell.textLabel?.text = statuses[indexPath.row].user?.name
        cell.status = statuses[indexPath.row]
        return cell
    }
}
